import { CSSProperties, memo, useCallback, useMemo, useState } from 'react';
import type { FC, PropsWithChildren } from 'react';
import { Link } from 'react-router-dom';
import {
  Button,
  CheckboxOptionType,
  Form,
  Image,
  Input,
  message,
  Popconfirm,
  Radio,
  Switch,
  Table,
  Tag,
} from 'antd';
import { ColumnsType } from 'antd/es/table';
import { resCategoryList } from '@/services/category';
import {
  resAddGoods,
  resChangeGoods,
  resDeleteGoods,
  resGoodsAdmin,
  resGoodsRecommendAdmin,
  resOnGoods,
} from '@/services/goods';
import { DeleteTwoTone, EditTwoTone } from '@ant-design/icons';
import { useAntdTable, useRequest } from 'ahooks';
import { isString } from 'lodash';
import EditModal from '@/components/EditModal';
import { orderNoStyle, style } from '@/pages/Profile/components/MyOrders';
import EditGoodsForm from '@/pages/Profile/components/MySell/EditGoodsForm';
import { formatTime, formatUrl } from '@/utils/format';
import {isRecommendOptions, OpenAndOperation} from "@/pages/Profile/components/MySell";

const createColumns = (
  refresh: () => void,
  showModal: (status: 'edit' | 'add', defaultValue?: API.GoodsStruct) => void
): ColumnsType<API.GoodsStruct> => [
  {
    title: <div className={' font-bold'}>图片</div>,
    dataIndex: 'cover',
    align: 'center',
    render: (cover) =>
      cover &&
      isString(cover) && (
        <Image src={formatUrl(cover)} alt="" width={40} height={64} />
      ),
  },
  {
    title: <div className={' font-bold'}>商品名称</div>,
    dataIndex: 'title',
    align: 'center',
    width: 150,
    render: (title, goods) => (
      <Link to={`/goods_detail/` + goods.id}>{title}</Link>
    ),
  },
  {
    title: <div className={' font-bold'}>价格</div>,
    dataIndex: 'price',
    align: 'center',
    render: (price) => (
      <div className={'text-base text-blue-600'}>
        <em className={'text-xs'}>￥</em>
        <span>{price}</span>
      </div>
    ),
    sorter: (a, b) => a.price - b.price,
  },
  {
    title: <div className={' font-bold'}>库存</div>,
    dataIndex: 'stock',
    align: 'center',
    sorter: (a, b) => a.stock - b.stock,
  },
  {
    title: <div className={' font-bold'}>销量</div>,
    dataIndex: 'sales',
    align: 'center',
    sorter: (a, b) => a.sales - b.sales,
  },
  {
    title: <div className={' font-bold'}>折扣</div>,
    dataIndex: 'discount',
    align: 'center',
    render: (discount) => <Tag color={'green'}>{discount * 100 + '%'}</Tag>,
  },
  {
    title: <div className={' font-bold'}>分类</div>,
    dataIndex: ['category', 'name'],
    align: 'center',
  },
  {
    title: <div className={' font-bold'}>创建时间</div>,
    dataIndex: 'created_at',
    align: 'center',
    render: (created_at) => formatTime(created_at),
  },
  {
    title: <div className={' font-bold'}>是否上架</div>,
    dataIndex: 'is_on',
    align: 'center',
    render: (is_on, goods) => (
      <Switch
        checked={Boolean(is_on)}
        onChange={() => {
          resOnGoods(goods.id).then(() => {
            refresh();
          });
        }}
      />
    ),
  },
  {
    title: <div className={' font-bold'}>是否推荐</div>,
    dataIndex: 'is_recommend',
    align: 'center',
    render: (is_recommend, goods) => (
      <Switch
        checked={Boolean(is_recommend)}
        onChange={() => {
          resGoodsRecommendAdmin(goods.id).then(() => {
            refresh();
          });
        }}
      />
    ),
  },
  {
    title: <div className={'font-bold'}>交易操作</div>,
    key: 'operate',
    render: (_, goods) => {
      return (
        <div>
          <Button
            type={'link'}
            icon={<EditTwoTone />}
            onClick={() => {
              showModal('edit', goods);
            }}
          />
          <Popconfirm
            title={'您确定要删除此商品吗'}
            cancelText="取消"
            okText="确定"
            onConfirm={() => {
              resDeleteGoods(goods.id).then(() => {
                message.success('删除商品成功！');
                refresh();
              });
            }}
          >
            <Button
              type={'link'}
              icon={<DeleteTwoTone twoToneColor={'red'} />}
            />
          </Popconfirm>
        </div>
      );
    },
  },
];


const isOnOptions: CheckboxOptionType[] = [
  {
    label: '已上架',
    value: '1',
  },
  {
    label: '未上架',
    value: '2',
  },
];


const GoodsManage: FC<PropsWithChildren<{}>> = () => {
  const [form] = Form.useForm();
  const { tableProps, pagination, search } = useAntdTable(
    (
      { pageSize, current },
      formData: Omit<API.QueryMyGoods, 'pageSize' | 'current'>
    ) => {
      return resGoodsAdmin({
        pageSize,
        current,
        ...formData,
      });
    },
    { form, cacheKey: 'useGoodsAdminCache' }
  );

  const refresh = () => {
    pagination.changeCurrent(pagination.current);
  };

  const { submit, reset } = search;

  const searchForm = (
    <div className={''}>
      <Form form={form} className={'flex'}>
        <Form.Item name="title">
          <Input.Search placeholder="请输入商品名" onSearch={submit} />
        </Form.Item>
        <Form.Item name={'is_on'} style={orderNoStyle}>
          <Radio.Group
            options={isOnOptions}
            optionType="button"
            buttonStyle="solid"
            onChange={() => {
              submit();
            }}
          />
        </Form.Item>
        <Form.Item name={'is_recommend'}>
          <Radio.Group
            options={isRecommendOptions}
            optionType="button"
            buttonStyle="solid"
            onChange={() => {
              submit();
            }}
          />
        </Form.Item>
        <div className={'px-5'}>
          <Button
            htmlType={'reset'}
            onClick={() => {
              reset();
            }}
          >
            重置
          </Button>
        </div>
        <div className={'ml-auto'}>
          <Button
            onClick={() => {
              showModal('add');
            }}
            type={'primary'}
          >
            新增
          </Button>
        </div>
      </Form>
    </div>
  );

  const { data, run } = useRequest(resCategoryList, { manual: true });

  const [isModalOpen, setIsModalOpen] = useState<OpenAndOperation>({
    show: false,
    defaultValue: {} as API.GoodsStruct,
    status: 'add',
  });
  const showModal = useCallback(
    (status: 'edit' | 'add', defaultValue?: API.GoodsStruct) => {
      setIsModalOpen({ show: true, defaultValue, status });
      run({});
    },
    []
  );
  const handleCancel = useCallback(
    () => setIsModalOpen({ ...isModalOpen, show: false }),
    [isModalOpen]
  );

  const columns = createColumns(refresh, showModal);

  const onFinish = useCallback(
    (value: any) => {
      value.category_id = value.category_id[value.category_id.length - 1];
      if (!isString(value.cover)) {
        value.cover = value.cover.file.response.data[0];
      }
      if (isModalOpen.status == 'add') {
        resAddGoods(value as API.AddGoodsParams).then(() => {
          message.success('添加商品成功');
          handleCancel();
          refresh();
        });
      } else if (isModalOpen.status == 'edit') {
        if (isModalOpen.defaultValue) {
          if (!value.category_id)
            value.category_id = isModalOpen.defaultValue.category_id;
          resChangeGoods(isModalOpen.defaultValue.id, value).then(() => {
            message.success('修改商品成功');
            handleCancel();
            refresh();
          });
        }
      }
    },
    [isModalOpen, refresh, handleCancel]
  );

  const editModal = (
    <EditModal
      title={isModalOpen.status == 'add' ? '添加商品' : '编辑商品'}
      isModalOpen={isModalOpen.show}
      onCancel={handleCancel}
      width={800}
    >
      <div className={'px-4'}>
        <EditGoodsForm
          onFinish={onFinish}
          data={data}
          defaultValue={
            isModalOpen.status === 'edit' ? isModalOpen.defaultValue : undefined
          }
        />
      </div>
    </EditModal>
  );

  return (
    <div style={style} className={'p-4 hidden-scrollbar'}>
      {searchForm}
      <div className={'rounded-lg overflow-hidden'}>
        <Table columns={columns} rowKey="id" {...tableProps} />
      </div>
      {editModal}
    </div>
  );
};

export default memo(GoodsManage);
